package com.xiaoka.ins.corp.api.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import javax.xml.bind.JAXBException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Component;

@Component
public class JaxbUtils {
	
	@Autowired
	private Jaxb2Marshaller jaxb2Marshaller;
	
	@SuppressWarnings("unchecked")
	public <T>T xmlToBean(String responseXml) throws JAXBException {
		return (T)jaxb2Marshaller.unmarshal(new StreamSource( new StringReader(responseXml) ) );
	}
	
	public <T>String beanToXml(T object) {
		return beanToXml(object,null);
	}
	
	public <T>String beanToXml(T object,Map<String,String> properties) {
		if(properties!=null){
			jaxb2Marshaller.setMarshallerProperties(properties);
		}
		StringWriter writer = new StringWriter();
		jaxb2Marshaller.marshal(object, new StreamResult(writer));
		return writer.toString();
	}
	 
	
	/**
	 * 读取指定xml转换为bean并返回
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public <T>T getObjByConfigXml(File file) throws FileNotFoundException{
		return (T)jaxb2Marshaller.unmarshal(new StreamSource(new FileInputStream(file)));
	}
	
	/**
	 * 将bean写入指定路径文件xml
	 * @param object
	 * @param file
	 * @throws FileNotFoundException
	 */
	public <T> void setConfigXmlByObj(T object,File file) throws FileNotFoundException{
		jaxb2Marshaller.marshal(object, new StreamResult(new FileOutputStream(file)));
	}
}
